<?php
/**
 * format $id 01 - 10/10/2009
 *
 * Get a Tree and Format to Array
 *
 * JLoja Project
 * @package    pack
 * @author     Joao Neto <joao_neto@ymail.com>
 * @version    0.1
 */

class JLoja_Db_Tree_Format
{

	/**
	 * @var Doctrine_Collection $_tree
	 */
	private $_tree;

	private $_rootColumnName = 'root_id';
	/**
	 * @param Doctrine_Collection $tree
	 */
	public function __construct( $tree )
	{
		$this->_tree = $tree;
	}

	public function getTree()
	{
		return $this->_tree;
	}

	public function setTree($_tree)
	{
		$this->_tree = $_tree;
	}

	public function get_tree() {
		return $this->_tree;
	}

	public function set_tree($_tree) {
		$this->_tree = $_tree;
	}

	public function getRootColumnName()
	{
		return $this->_rootColumnName;
	}

	public function setRootColumnName($_rootColumnName)
	{
		$this->_rootColumnName = $_rootColumnName;
	}


	public function format( )
	{
		$treeArr = $this->_tree;
		$rootColumnName = $this->_rootColumnName;
		//fetchTheRoots
		foreach( $treeArr as $key => $tree ){
			if( $tree->level == '0' ){
				$roots[ $tree->$rootColumnName ][ 'obj' ] = $tree->toArray();
				unset( $treeArr[ $key ] );
			}
		}

		$roots = $this->_appendChild( $treeArr, $roots );

	}

	public function getRoots()
	{
		$roots = clone $this->_tree;
		foreach( $roots as $key=> $tree ){
			if( $tree->level != 0 ){
				unset( $roots[ $key ] );
			}
		}

		return $roots;
	}

	public function hasChildren( $root )
	{
		return (($root->rgt - $root->lft ) >1 );

	}

	public function fetchAll( )
	{
		return $this->_tree;
	}
	
	public function getChildren( $record, $a = 0 )
	{
		$lft = $record->lft;
		$rgt = $record->rgt;
		$root = $record->{$this->_rootColumnName};
		$level = $record->level + 1;
		$tree = clone $this->_tree;

		foreach( $tree as $key => $t ){
			if( !( $t->lft > $lft && $t->rgt < $rgt && $t->{$this->_rootColumnName} == $root && $t->level <= $level ) ){
				unset( $tree[ $key ] );
				echo 'Filho';
			}
		}
		
		return $tree;
	}
	private function _appendChild( $child, $roots, $level = 1 )
	{

	}
}